<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Landing Page - Start Bootstrap Theme</title>
    <!-- Bootstrap core CSS -->
    <link href="static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom fonts for this template -->
    <link href="static/vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
    <link href="static/vendor/simple-line-icons/css/simple-line-icons.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">
    <!-- Custom styles for this template -->
    <link href="static/css/landing-page.min.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <div class="container">
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarTogglerDemo01">
                <a class="navbar-brand" href="/">
                    <img src="static/img/nav.png" style="width:40px;" alt="Barış"/>
                </a>
                <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
                    <li class="nav-item active">
                        <a class="nav-link" href="/">Anasayfa <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/DetectorWebcam">WebCam</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/DetectorStreamGet">Uplaod Video</a>
                    </li>
                </ul>
            </div>    
        </div>
    </nav>

    <div class="container">
		<div class="row">
            <div class="col-md-12 text-center">
				<span>Gerçek Zaman : </span>
				<span id="timeReal"></span>
            </div>
        </div>
		<div class="row">
            <div class="col-md-12 text-center">
                <video id="video" height="480" autoplay style="max-width:640px;border:1px dashed #000;margin-top: 30px;"></video>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12 text-center">
                <button class="btn btn-block btn-primary" id="startCamera" style="max-width:640px;margin:0 auto;">Start Camera</button>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12 text-center" style="padding-top:30px;">
                <h3 style="color:green" class="result"></h3>
                <h3 style="color:green" class="resultTime"></h3>
				<div class="box-fight">
				</div>
                <canvas id="canvas" width="640" height="480" style="visibility:hidden;"></canvas>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer bg-light" style="padding:20px 0px;text-align:center;">
        <div class="container">
            <p class="text-muted small mb-4 mb-lg-0">&copy; Your Website 2019. All Rights Reserved.</p>
        </div>
    </footer>
    <!-- Bootstrap core JavaScript -->
    <script src="static/vendor/jquery/jquery.min.js"></script>
    <script src="static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="static/js/socket.io.min.js"></script>

	<script type="text/javascript">
		var socket = io.connect('http://' + document.domain + ':' + location.port);
		socket.on( 'connect', function(){});
		var video = document.getElementById('video');
		var canvas = document.getElementById('canvas');
		var context = canvas.getContext('2d');
		var stateFight=false;
		var frames=[];
		var maxFrames=1000;
		var img;
		var counterFightYes=0;
		var counterFightNo=0;
		var counterLostFrame=0;

		var counterStart=0;
		var counterEnd=0;
        var lastTime="";
        var start=[];
        var end=[];
        var counterPush=6000;


		function sendFrames(){
			if(frames.length >= 10){
                socket.emit('SocketDetectorWebcam',{
					data: frames
				});
				isReceiveResponse=false;
				frames=[];
			}else{
				setTimeout(sendFrames,2000);
			}
		}
		function setFrames(){
			setTimeout(function(){ 
				context.drawImage(video, 0, 0, 640, 480);
				img = canvas.toDataURL("image/jpeg");
				var now=new Date();
				var frameData={
					img:img,
					time:now.getHours()+":"+now.getMinutes()+":"+now.getSeconds(),
					counterStart:counterStart,
					counterEnd:counterEnd
				};
				if(frames.length>=maxFrames){
					frames.shift();
					counterLostFrame++;
				}
                frames.push(frameData);
				setFrames();
			}, 50);
		}
		socket.on('SocketDetectorComplete',function(message){
            if(message.isDone!=undefined){
                if(message.listStreamStart.length == message.listStreamEnd.length){
                    $(".result").text("ŞİDDET YOK");
                    $(".result").css("color","green");
                    $(".resultTime").text(message.time);
                    $(".resultTime").css("color","green");
                    counterFightNo++;
                    if(message.listStreamEnd[message.listStreamEnd.length-1]!=undefined){
                        if(end.indexOf(message.listStreamEnd[message.listStreamEnd.length-1])==-1){
                            end.push(message.listStreamEnd[message.listStreamEnd.length-1]);
                            txtFight=' - Şiddet Bitiş : <span style="color:red">'+message.listStreamEnd[message.listStreamEnd.length-1]+'</span><br/>';
                            $(".box-fight").append(txtFight);
                            txtFight="";
                        }
                    }
                }else{
                    $(".result").text("ŞİDDET VAR");
                    $(".result").css("color","red");
                    $(".resultTime").text(message.time);
                    $(".resultTime").css("color","red");
                    counterFightYes++;
                    if(start.indexOf(message.listStreamStart[message.listStreamStart.length-1])==-1){
                        start.push(message.listStreamStart[message.listStreamStart.length-1]);
                        txtFight='Şiddet Baslangıç : <span style="color:red">'+message.listStreamStart[message.listStreamStart.length-1]+'</span>';
                        $(".box-fight").append(txtFight);
                        txtFight="";
                    }
                    if(counterPush/60>=5){
                        $.ajax({
                            type: "POST",
                            beforeSend: function (xhr) {
                                xhr.setRequestHeader('Authorization', 'Bearer o.baI8rwqroFcWZlJQj8ocrFJk7wcn3Qam');
                            },
                            url: "https://api.pushbullet.com/v2/pushes",
                            data: {"type": "note", "title": "Şiddet Tespit Edildi!", "body": "Şiddet zamanı : "+message.listStreamStart[message.listStreamStart.length-1]},
                            success: function(success){
                                console.log("push notification başarılı")
                            }
                        });
                        counterPush=0;
                    }
                }
            }else{
                if(message.isFight=='true'){
                    $(".result").text("ŞİDDET VAR");
                    $(".result").css("color","red");
                    $(".resultTime").text(message.time);
                    $(".resultTime").css("color","red");
                }else if(message.isFight=='false'){
					$(".result").text("ŞİDDET YOK");
                    $(".result").css("color","green");
                    $(".resultTime").text(message.time);
                    $(".resultTime").css("color","green");
                }
				if(message.isComplete=='true'){
					sendFrames();
				}
            }
		});
		$(document).ready(function(){
			$('#startCamera').click(function(){
				var status=false;
				// Kamerayi aktiflestir!
				if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
					navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
						video.srcObject = stream;
						video.play();
						setFrames();
						setTimeout(sendFrames,2000);
					});
				}
				else if(navigator.getUserMedia) { 
					// Standard
					navigator.getUserMedia({ video: true }, function(stream) {
						video.src = stream;
						video.play();
						setFrames();
						setTimeout(sendFrames,2000);
					}, errBack);
				} else if(navigator.webkitGetUserMedia) { 
					// WebKit-prefixed
					navigator.webkitGetUserMedia({ video: true }, function(stream){
						video.src = window.webkitURL.createObjectURL(stream);
						video.play();
						setFrames();
						setTimeout(sendFrames,2000);
					}, errBack);
				} else if(navigator.mozGetUserMedia) { 
					// Mozilla-prefixed
					navigator.mozGetUserMedia({ video: true }, function(stream){
						video.srcObject = stream;
						video.play();
						setFrames();
						setTimeout(sendFrames,2000);
					}, errBack);
				}
				setInterval(zamanGoster, 1000);
				function zamanGoster () {
					var saat = new Date();
					document.getElementById("timeReal").innerHTML = "Gerçek Zaman : "+saat.toLocaleTimeString();
                    counterPush++;
				}
			});
		});
	</script>
</body>
</html>
